#include <system/config_system.h>
#include <utl/vector.h>
#include <fstream>

constexpr auto config_default_path{ "primary.cfg" };

utl::vector<primal::ConfigBinding*> all_config_bindings;

bool initialize_setting(primal::Setting& st)
{
    std::ifstream ifile{ config_default_path };
    if(ifile.is_open())
    {
        return st.ParseFromIstream(&ifile);
    }
    return true;
}

primal::Setting& primal::setting()
{
    static primal::Setting st{};
    static bool is_setting_invalid{ initialize_setting(st) };
    assert(is_setting_invalid);
    return st;
}

void primal::setting_changed(SettingBlock block)
{
    for(auto& item : all_config_bindings)
    {
        item->on_setting(block);
    }
}

bool primal::save_setting()
{
    std::ofstream ofile{ config_default_path };
    return setting().SerializeToOstream(&ofile);
}

primal::ConfigBinding::ConfigBinding()
{
    all_config_bindings.push_back(this);
}

primal::ConfigBinding::~ConfigBinding()
{
    utl::vector_delete_element(all_config_bindings, this);
}